package com.katesoft.scale4j.demo.services;

import com.katesoft.scale4j.demo.domain.Currency;
import com.katesoft.scale4j.log.Logger;
import com.katesoft.scale4j.log.LogFactory;
import com.katesoft.scale4j.persistent.client.LocalHibernateTemplate;
import com.katesoft.scale4j.persistent.model.unified.AbstractPersistentEntity;
import org.apache.commons.io.IOUtils;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;
import java.util.Collection;
import java.util.LinkedHashSet;

import static com.katesoft.scale4j.persistent.utils.DataAccessUtility.fetchFirstRowOrNull;

public class AvailableCurrenciesTasklet implements Tasklet
{
    private Logger logger = LogFactory.getLogger(getClass());
    private RestTemplate template = new RestTemplate();
    private LocalHibernateTemplate hibernateTemplate;

    @SuppressWarnings({"unchecked"})
    @Override
    public RepeatStatus execute(StepContribution contribution,
                                ChunkContext chunkContext)
    {
        String s = template.getForObject("http://currencies.apps.grandtrunk.net/currencies", String.class);
        logger.info(s);
        BufferedReader reader = new BufferedReader(new StringReader(s));
        Collection<Currency> currencies = new LinkedHashSet<Currency>();
        try {
            String code;
            while ((code = reader.readLine()) != null) {
                currencies.add(new Currency(code));
            }
            logger.debug("there are %s available currencies, will persist them", currencies.size());
            for (Currency currency : currencies) {
                Currency example = new Currency();
                example.cleanBeanProperties();
                example.setCode(currency.getCode());
                AbstractPersistentEntity obj = fetchFirstRowOrNull(hibernateTemplate.findByExample(example));
                if (obj == null) {hibernateTemplate.save(currency);}
            }
        }
        catch (IOException e) {
            logger.error(e);
        }
        finally {
            IOUtils.closeQuietly(reader);
        }
        hibernateTemplate.flush();
        return RepeatStatus.FINISHED;
    }

    @Autowired
    @Required
    public void setHibernateTemplate(LocalHibernateTemplate hibernateTemplate)
    {
        this.hibernateTemplate = hibernateTemplate;
    }
}
